package com.example.demo.controller;

import com.example.demo.vo.CommonResult;
import com.example.demo.vo.ProcessDeployVo;
import com.example.demo.vo.ProcessFormVo;
import com.example.demo.vo.TaskVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.camunda.bpm.engine.*;
import org.camunda.bpm.engine.history.HistoricTaskInstance;
import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.engine.repository.DeploymentBuilder;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@Api(value = "CamundaProcessController", tags = "流程控制表")
public class CamundaProcessController {
    @Autowired
    private RuntimeService runtimeService;

    private ProcessEngine processEngine;
    @Autowired
    private IdentityService identityService;
    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;


    @PostMapping("/user/{processKey}")
    @ApiOperation(value = "启动流程", tags = "流程管理", notes = "开启流程")
    public CommonResult<String> startFlow(@PathVariable(value = "processKey") String processKey) {
        identityService.setAuthenticatedUserId("cc");
        final VariableMap variables = Variables.createVariables();
        variables.putValue("initiator", "cc");
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processKey, variables);

        return  CommonResult.success(processInstance.getProcessDefinitionId());

    }

    @PostMapping("/deployFlow")
    @ApiOperation(value = "发布流程", tags = "流程管理", notes = "发布流程")
    //TODO 还未调试通 需要查看源码
    public CommonResult<Deployment> deployFlow(@RequestBody ProcessDeployVo processDeployVo) throws FileNotFoundException {
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        RepositoryService repositoryService = processEngine.getRepositoryService();
        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();

        InputStream inputStream =new FileInputStream(new File(processDeployVo.getResourcePath()));
        deploymentBuilder.addInputStream(processDeployVo.getResourceName(),inputStream);
        Deployment deployment = deploymentBuilder.deploy();

        return  CommonResult.success(deployment);

    }


    @PostMapping("/撤回任务")
    @ApiOperation(value = "撤回任务", tags = "流程管理", notes = "发布流程")
    public CommonResult<Boolean>  backFlow(@RequestBody ProcessFormVo processDeployVo) throws FileNotFoundException {

        return  CommonResult.success();

    }

    @ApiOperation("5、终止流程")
    @PostMapping("/terminate/process")
    public CommonResult<Boolean> terminateProcess (@Validated @RequestBody ProcessFormVo vo) {
        runtimeService.deleteProcessInstance(vo.getProcessInstanceId(), "手动删除");
        return  CommonResult.success();

    }


    @PostMapping("/task/list/{userId}")
    @ApiOperation(value = "获取代办列表", tags = "流程管理", notes = "获取代办列表")
    public CommonResult<List<TaskVo>> taskList(@PathVariable("userId") String userId) {
        final List<Task> list = taskService.createTaskQuery()
                .taskAssignee(userId).list();
        List<TaskVo> dtoList = new ArrayList<>();
        for (Task task : list) {
            TaskVo dto = new TaskVo();
            dto.setId(task.getId());
            dto.setName(task.getName());
            dto.setAssignee(task.getAssignee());
            dto.setCreateTime(task.getCreateTime());
            dtoList.add(dto);
        }
        return CommonResult.success(dtoList);
    }


    @PostMapping("/task/complete")
    @ApiOperation(value = "完成流程节点", tags = "流程管理", notes = "完成流程节点")
    public String complete(@RequestBody HashMap<String, Object> params) {
        final String id = String.valueOf(params.get("id"));
        final Task task = taskService.createTaskQuery().taskId(id).singleResult();
        if (task == null) {
            return "该任务不存在";
        }
        VariableMap variables = Variables.createVariables();
        for (String key : params.keySet()) {
            Object value = params.get(key);
            if (value instanceof Integer) {
                variables.putValue(key, Long.parseLong(params.get(key).toString()));
            } else {
                variables.putValue(key, params.get(key));
            }
        }
        taskService.complete(id, variables);
        return "请求成功";
    }
    @GetMapping("/getHistoryTaskList/list/{userId}")
    @ApiOperation(value = "根据userId获取完成节点信息", tags = "流程管理", notes = "根据userId获取完成节点信息")
    public List<HistoricTaskInstance> getHistoryTaskList(@PathVariable("userId") String userId) {
        return historyService.createHistoricTaskInstanceQuery().taskAssignee(userId).finished().list();
    }
    @GetMapping("/getUnfinishedHistoryTaskList/list/{userId}")
    @ApiOperation(value = "根据userId获取未完成节点信息", tags = "流程管理", notes = "根据userId获取完成节点信息")
    public List<HistoricTaskInstance> getUnfinishedHistoryTaskList(@PathVariable("userId") String userId) {
        return historyService.createHistoricTaskInstanceQuery().taskAssignee(userId).unfinished().list();
    }
    @GetMapping("/forceCloseProcessInstance/{processInstanceId}")
    @ApiOperation(value = "强制关闭流程", tags = "流程管理", notes = "根据userId获取完成节点信息")
    public List<HistoricTaskInstance> forceCloseProcessInstance(@PathVariable("processInstanceId") String processInstanceId) {

        RuntimeService service = processEngine.getRuntimeService();

        //service.t
        return null;
    }
}